package com.naizhuai.util;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;

import com.naizhuai.AppContext;
import com.naizhuai.ui.entity.AnlyParamsBean;
import com.naizhuai.ui.entity.ImageBean;

import java.io.File;

/**
 * 文件名的修改以及创建
 * Created by code_han on 2018/3/29.
 */

public class FileNameUtils {
    public static final String SPLIT = "_";

    public static final String CACHE_FILE = "cache" + SPLIT;
    public static final String MERGE_FILE = "merge" + SPLIT;

    public static final int IS_CACHE_FILE = 0;
    public static final int NOT_CACHE_FILE = 1;
    public static final int IS_MERGE_FILE = 2;


    // 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
    @SuppressLint("NewApi")
    public static String getPathByUri4kitkat(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {// MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
            // (and
            // general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    /**
     * 获取app缓存路径
     *
     * @param context
     * @return
     */
    private static String getCachePath(Context context) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            //外部存储可用
            NaizhuAILog.e("Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()");
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            //外部存储不可用
            NaizhuAILog.e("外部存储不可用");
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    public static String createFileNamePath(Context mContext, String path, int fileType) {
//        String newPath = path.replace("/", SPLIT);
        String fileName = path.substring(path.lastIndexOf(File.separator) + 1);
        if (fileType == IS_CACHE_FILE)
            fileName = CACHE_FILE + fileName;
        if (fileType == IS_MERGE_FILE)
            fileName = MERGE_FILE + fileName;
        return getCachePath(mContext) + File.separator + fileName;
    }

    //通过path判断文件是否存在
    public static AnlyParamsBean<File> isExistFileByName(Context mContext, String nameStr) {
        String path = createFileNamePath(mContext, nameStr, NOT_CACHE_FILE);
        File file = new File(path);
        return new AnlyParamsBean<>(file.exists(), file);
    }

    //获取image的input Uri
    public static Uri getInputUri(String fileName, Context mContext) {
        return file2Uri(mContext, new File(createFileNamePath(mContext, fileName, NOT_CACHE_FILE)));
    }

    //获取image的output Uri
    public static Uri getCacheUri(String fileName, Context mContext) {
        return file2Uri(mContext, new File(createFileNamePath(mContext, fileName, IS_CACHE_FILE)));
    }

    /**
     * 根据文件转换成对应的Uri
     *
     * @param ctx
     * @param file
     * @return
     */
    public static Uri file2Uri(Context ctx, File file) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            return FileProvider.getUriForFile(ctx, ctx.getPackageName()+ ".fileprovider", file);
//        } else {
        return Uri.fromFile(file);
//        }
    }

    /**
     * 根据文件路径转换成对应的Uri
     *
     * @param filePath
     * @return
     */
    public static Uri filePath2Uri(String filePath) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            return FileProvider.getUriForFile(ctx, ctx.getPackageName()+ ".fileprovider", file);
//        } else {
        return Uri.fromFile(new File(filePath));
//        }
    }

    public static String getFileType(String fileName) {
        String[] splits = fileName.split("\\.");
        return splits[splits.length - 1];
    }

    public static boolean isSuitableType(String fileName,String...types){
        String type=getFileType(fileName);
        for (String file:types) {
            if(file.equalsIgnoreCase(type))
                return true;
        }
        return false;
    }
}
